package com.woniuxy.controller;

import com.nimbusds.jose.JOSEException;
import com.woniuxy.entity.DTO.ChangePasswordDTO;
import com.woniuxy.entity.DTO.ReceivingOrderDTO;
import com.woniuxy.entity.DTO.SorterDTO;
import com.woniuxy.entity.DTO.SortingDTO;
import com.woniuxy.service.CourierService;
import com.woniuxy.service.SorterService;
import com.woniuxy.util.MinioUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.UserContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sorter")
public class SorterController {
    @Resource
    private SorterService sorterService;

    @Resource
    private CourierService courierService;

    @Resource
    private MinioUtil minioUtils;

    @GetMapping("/querySorterList")
    public ResponseData querySorterList() {
        List<SorterDTO> sorterDTOS = sorterService.querySorterList();
        return ResponseData.success(sorterDTOS);
    }

    @PostMapping("/saveAddSorter")
    public ResponseData saveAddSorter(@RequestBody SorterDTO sorterDTO) {
        Integer integer = sorterService.updateSorterById(sorterDTO.getId(), sorterDTO.getWarehouseId());
        return ResponseData.success(integer);
    }

    @GetMapping("/querySorterByCondition/{warehouseId}")
    public ResponseData querySorterByCondition(@PathVariable Integer warehouseId) {
        List<SorterDTO> sorterDTOS = sorterService.querySorterByWarehouseId(warehouseId);
        return ResponseData.success(sorterDTOS);
    }

    @PostMapping("/querySorterByName")
    public ResponseData querySorterByName(@RequestBody SorterDTO sorterDTO) {
        List<SorterDTO> sorterDTOS = sorterService.querySorterByName(sorterDTO.getSorterName(), sorterDTO.getWarehouseId());
        return ResponseData.success(sorterDTOS);
    }

    @GetMapping("/sorterUnbind/{id}")
    public ResponseData sorterUnbind(@PathVariable Integer id) {
        sorterService.sorterUnbind(id);
        return ResponseData.success();
    }

    @PostMapping("/register")
    public ResponseData register(@RequestBody SorterDTO sorterDTO) throws NoSuchAlgorithmException {
        // 增加详细的日志记录
        System.out.println("收到注册请求：" + sorterDTO);
        boolean b = sorterService.querySorterByAccount(sorterDTO.getSorterAccount());
        if (b) {
            return ResponseData.fail(ResponseEnum.ACCOUNT_EXISTS_FAIL);
        }
        boolean register = sorterService.register(sorterDTO);
        return ResponseData.success(register);
    }

    @PostMapping("/login")
    public ResponseData login(@RequestBody SorterDTO sorterDTO) throws JOSEException {
        // 增加详细的日志记录
        System.out.println("收到登录请求：" + sorterDTO);
        ResponseData login = sorterService.login(sorterDTO);
        if(login.getCode() == ResponseEnum.SUCCESS.getCode()){
            return ResponseData.success(login);
        }else{
            return ResponseData.fail(ResponseEnum.LOGIN_FAIL);
        }


    }

    @GetMapping("/profile")
    public ResponseData getProfile(@RequestParam("sorterAccount") String sorterAccount) {
        System.out.println("收到传来的账号信息" + sorterAccount);
        // 根据 sorterAccount 查询用户信息
        SorterDTO sorterDTO = sorterService.queryProfileByAccount(sorterAccount);
        // 返回用户详细信息
        return ResponseData.success(sorterDTO);
    }

    @PostMapping("/changePassword")
    public ResponseData changePassword(@RequestBody ChangePasswordDTO changePasswordDTO) {
        System.out.println("账号:" + changePasswordDTO.getAccount() + "旧密码" + changePasswordDTO.getOldPassword() + "新密码" + changePasswordDTO.getNewPassword());
        // 根据 sorterAccount 查询用户信息
        boolean b = sorterService.updatePasswordByName(changePasswordDTO);
        // 返回用户详细信息
        return ResponseData.success(b);
    }

    @GetMapping("/available-orders")
    public ResponseData availableOrder(@RequestParam("warehouseId") Integer warehouseId) {
        System.out.println("收到传来的仓库ID" + warehouseId);
        // 根据 sorterAccount 获取仓库的订单
        List<ReceivingOrderDTO> receivingOrderDTOS = sorterService.queryOrdersByWarehouseId(warehouseId);
        // 获取仓库的订单
        return ResponseData.success(receivingOrderDTOS);
    }

    @PostMapping("/receive")
    public ResponseData receive(@RequestBody Map<String, Object> requestBody) throws ParseException {
        // 通过 UserContext 获取当前用户ID
        Integer sorterId = UserContext.getUserId();

        // 从请求体中获取 orderIds
        List<String> orderIds = (List<String>) requestBody.get("orderIds");

        // 打印日志
        System.out.println("收到传来的订单ID列表：" + orderIds);
        System.out.println("分拣员ID：" + sorterId);

        boolean b = sorterService.updateSorting(sorterId, orderIds);

        return ResponseData.success(b);
    }

    @GetMapping("/my-orders")
    public ResponseData myOrders() throws ParseException {
        // 通过 UserContext 获取当前用户ID
        Integer sorterId = UserContext.getUserId();

        // 获取改分拣员用户对应的订单
        List<ReceivingOrderDTO> receivingOrderDTOS = sorterService.queryOrdersBySorterId(sorterId);

        // 打印日志
        System.out.println("收到传来的订单ID列表：" + receivingOrderDTOS);
        System.out.println("分拣员ID：" + sorterId);

        return ResponseData.success(receivingOrderDTOS);
    }

    @PostMapping("/myOrderTask")
    public ResponseData myOrderTask(@RequestBody SortingDTO sortingDTO) {
        System.out.println(sortingDTO);
        boolean b = sorterService.updateSortingStatus(sortingDTO.getOrderId());
        System.out.println(sortingDTO);
        courierService.insertCourierInfo(sortingDTO.getOrderId(),sortingDTO.getWarehouseId());
        return ResponseData.success(b);
    }

    @GetMapping("/orderGoods")
    public ResponseData orderGoods(@RequestParam("orderId") String orderId) {
        System.out.println("收到传来的订单ID" + orderId);
        // 根据 sorterAccount 查询用户信息
        List<ReceivingOrderDTO> receivingOrderDTOS = sorterService.queryOrderGoods(orderId);
        // 返回用户详细信息
        return ResponseData.success(receivingOrderDTOS);
    }

    @GetMapping("/performance")
    public ResponseData getPerformanceData(
            @RequestParam(value = "timeType", defaultValue = "day") String timeType) throws ParseException {
        // 通过 UserContext 获取当前用户ID
        Integer sorterId = UserContext.getUserId();
        System.out.println(sorterId);
        // 根据 timeType 选择不同的查询逻辑
        if ("day".equals(timeType)) {
            // 查询当天的业绩数据
            Integer dailyPerformance = sorterService.getDailyPerformance(sorterId);
            return ResponseData.success(dailyPerformance);
        } else if ("month".equals(timeType)) {
            // 查询当月的业绩数据
            Integer monthlyPerformance = sorterService.getMonthlyPerformance(sorterId);
            return ResponseData.success(monthlyPerformance);
        } else {
            // 处理无效的 timeType
            return ResponseData.fail(ResponseEnum.NO_LOGIN.INVAILD_TIME_TYPE);
        }
    }

    @PostMapping("/imgLoad")
    public ResponseData imgLoad(MultipartFile file, HttpServletRequest request){
        try {
            String imgPath = minioUtils.uploadFile(file, "image");
            Integer userId = UserContext.getUserId();
            sorterService.imgLoad(userId, imgPath);
            return ResponseData.success(imgPath);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
